package demo.tencent;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.codec.digest.HmacAlgorithms;
import org.apache.commons.codec.digest.HmacUtils;
import org.junit.Ignore;
import org.junit.Test;

import javax.crypto.Mac;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.security.MessageDigest;

/**
 *
 * http://commons.apache.org/proper/commons-codec/archives/1.11/apidocs/org/apache/commons/codec/digest/HmacUtils.html
 *
 *
 *
 */
public class HmacSHA256 {

    public static final String SRC_DATA = "GETcvm.api.qcloud.com/v2/index.php?Action=DescribeInstances&InstanceIds.0=ins-09dx96dg&Nonce=11886&Region=ap-guangzhou&SecretId=AKIDz8krbsJ5yKBZQpn74WFkmLPx3gnPhESA&SignatureMethod=HmacSHA256&Timestamp=1465185768";

    public static final String secretKey = "Gu5t9xGARNpq86cd98joQYCN3Cozk1qA";

    @Test
    @Ignore
    public void test01(){
        Mac hmacSha256 = HmacUtils.getInitializedMac(HmacAlgorithms.HMAC_SHA_256, "hello".getBytes());
        System.out.println(String.valueOf(hmacSha256.doFinal()));
        System.out.println(hmacSha256.toString());
        System.out.println(hmacSha256.getAlgorithm());
    }

    @Test
    public void test02() throws UnsupportedEncodingException {
//        DigestUtils.getSha256Digest();
        String inputStr = new String("hello");
        System.out.println(DigestUtils.sha256Hex(inputStr));
        inputStr = "你好";
        System.out.println(DigestUtils.sha256Hex(inputStr.getBytes("UTF-8")));
        System.out.println(DigestUtils.sha256Hex(inputStr));

    }

    @Test
    public void test03(){
        System.out.println("=== begin === " + System.currentTimeMillis());

        Mac hmacSha256 =
                HmacUtils.getInitializedMac(HmacAlgorithms.HMAC_SHA_256, secretKey.getBytes());
        System.out.println("=== after init ===" + System.currentTimeMillis());
        byte[] rawHmac = hmacSha256.doFinal(SRC_DATA.getBytes());
        String hexString = Hex.encodeHexString(rawHmac, true);
//        char[] hex = new Hex(Charset.forName("ISO-8859-1")).encodeHex(rawHmac);
//        String hexString = new String(hex);
        String base64String = Base64.encodeBase64String(hexString.getBytes());

        System.out.println(base64String);
        System.out.println(hexString);
        System.out.println("=== end === " + System.currentTimeMillis());
    }

    @Test public void test04() throws Exception {
        String signature = PhpHashHmac.getSignature(PhpHashHmac.HMAC_SHA_256, SRC_DATA, secretKey);

        System.out.println(signature);
    }

}
